package com.wink.admin.aspect;

import com.wink.admin.aspect.annotation.RepeatSubmit;
import com.wink.admin.common.exception.CustomException;
import com.wink.admin.redis.RedisService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Optional;

/**
 * 重复提交切面
 *
 * @author xw
 * @date 2020-11-16 17:13
 */
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class RepeatSubmitAspect {

    private final RedisService redisService;

    /**
     * 解析器
     */
    private static ExpressionParser parser = new SpelExpressionParser();

    /**
     * 名字解析器
     */
    private static ParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();

    private final static String REPEAT_SUBMIT_KEY = "REPEAT_SUBMIT_KEY:%s#%s#%s#%s";


    @Pointcut("@annotation(com.wink.admin.aspect.annotation.RepeatSubmit)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //目标类、方法、注解参数
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();
        Object[] args = joinPoint.getArgs();
        RepeatSubmit repeatSubmit = method.getAnnotation(RepeatSubmit.class);

        //获得业务key
        String spelDefinitionKey = getSpelDefinitionKey(repeatSubmit.keys(), method, joinPoint.getArgs());

        String key = String.format(REPEAT_SUBMIT_KEY, spelDefinitionKey, className, methodName, Arrays.toString(args));

        Boolean setnx = redisService.setnx(key, 1, repeatSubmit.expire());
        if (!setnx) {
            throw new CustomException(repeatSubmit.message());
        }

        return joinPoint.proceed();
    }

    /**
     * 得到spel表达式参数key
     *
     * @param definitionKey   定义关键
     * @param method          方法
     * @param parameterValues 参数值
     * @return String
     * @author xw
     * @date 2020/4/13 17:36
     */
    private String getSpelDefinitionKey(String definitionKey, Method method, Object[] parameterValues) {
        if (definitionKey != null && !definitionKey.isEmpty()) {
            EvaluationContext context = new MethodBasedEvaluationContext(null, method, parameterValues, nameDiscoverer);
            return Optional.ofNullable(parser.parseExpression(definitionKey).getValue(context)).orElse("null").toString();
        }
        return null;
    }
}
